import { UserOutlined, KeyOutlined } from "@ant-design/icons";
import "./login.css";
import { Button, Space, Input } from "antd";
import { useState, useEffect } from "react";
import { getLogin } from "../tools/ajax";
import { useNavigate } from "react-router-dom";

export default function About(props) {
  let [username, setUsername] = useState("");
  let [password, setPassword] = useState("");
  let [usererr, setUsererr] = useState("");
  let [pwderr, setPwderr] = useState("");
  const navigate = useNavigate();

  async function login() {
    // 用户名正则验证
    var patt = /^[\w\u4e00-\u9fa5]{2,8}$/;
    if (!patt.test(username)) {
      setUsererr("只能包含数字、字母、下划线、汉字2-8位");
      return false;
    }

    // 密码正则验证
    var patt2 = /^\w{6,12}$/;
    if (!patt2.test(password)) {
      setPwderr("只能包含数字、字母、下划线6-12位");
      return false;
    }

    let { data: res } = await getLogin({
      userName: username,
      password: password,
    });
    console.log(res);

    if (res.code) {
      localStorage.setItem("token",res.token);
      navigate("/home");

    } else {
      alert("用户名或密码错误");
    }
  }

  return (
    <div className="logins">
      <Input
        size="large"
        placeholder="用户名"
        prefix={<UserOutlined />}
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
        style={{
          width: 400,
          height: 40,
        }}
      />
      <br />
      <br />
      {usererr ? <span>{usererr}</span> : ""}
      <Input.Password
        size="large"
        placeholder="密码"
        prefix={<KeyOutlined />}
        value={password}
        onChange={(e) => {
          setPassword(e.target.value);
        }}
        onFocus={() => {
          pwderr = "";
        }}
        style={{
          width: 400,
          height: 40,
        }}
      />
      <br />
      <br />
      {pwderr ? <span>{pwderr}</span> : ""}
      <Space wrap>
        <Button
          type="primary"
          style={{
            width: 400,
            height: 40,
          }}
          onClick={login}
        >
          登录
        </Button>
      </Space>
    </div>
  );
}
